package com.ebt.m.proposal_v2.mvp.presenter;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import com.ebt.m.AppContext;
import com.ebt.m.AppInitService;
import com.ebt.m.commons.utils.ActivityUtils;
import com.ebt.m.commons.utils.RxUtil;
import com.ebt.m.customer.entity.CustomerDetail;
import com.ebt.m.customer.event.EventCustomerListRefresh;
import com.ebt.m.customer.net.json.CustomerCRUDRetJson;
import com.ebt.m.customer.net.json.CustomerDetailJson;
import com.ebt.m.data.entity.Customer;
import com.ebt.m.data.rxModel.api.EBTAPI;
import com.ebt.m.event.EventRefreshProposalList;
import com.ebt.m.event.ProposalListTabCheckedEvent;
import com.ebt.m.proposal_v2.bean.ArgProposalDetail;
import com.ebt.m.proposal_v2.bean.InsuranceEntity;
import com.ebt.m.proposal_v2.bean.InsuredEntity;
import com.ebt.m.proposal_v2.bean.ProposalEntity;
import com.ebt.m.proposal_v2.dao.ProposalApi;
import com.ebt.m.proposal_v2.dao.request.DraftParam;
import com.ebt.m.proposal_v2.dao.request.ParamGetRisks;
import com.ebt.m.proposal_v2.dao.request.ProposalParam;
import com.ebt.m.proposal_v2.dao.response.BusinessConfig;
import com.ebt.m.proposal_v2.dao.response.ResponseChanShuoItem;
import com.ebt.m.proposal_v2.dao.response.ResponseDraft;
import com.ebt.m.proposal_v2.dao.response.ResponseMainDetail;
import com.ebt.m.proposal_v2.dao.response.ResponseMakeProposal;
import com.ebt.m.proposal_v2.dao.response.ResponsePickNum;
import com.ebt.m.proposal_v2.dao.response.ResponseProductProperties;
import com.ebt.m.proposal_v2.mvp.base.BasePresenter;
import com.ebt.m.proposal_v2.mvp.contract.ProposalMakeContract;
import com.ebt.m.proposal_v2.retrofit.OnResponseListener;
import com.ebt.m.proposal_v2.retrofit.ResponseBodyBase;
import com.ebt.m.proposal_v2.retrofit.ResponseError;
import com.ebt.m.proposal_v2.retrofit.ResponsePage;
import com.ebt.m.proposal_v2.ui.MainProductActivity;
import com.ebt.m.proposal_v2.ui.MakeProposalActivity;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.utils.GsonUtil;

import org.greenrobot.eventbus.EventBus;

import java.util.List;

import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

/**
 * @author archer.qi
 * Created on 2017/5/15.
 */
public class ProposalMakePresenter extends BasePresenter<ProposalMakeContract.View> implements ProposalMakeContract.Presenter {

    public ProposalMakePresenter(Context context, ProposalMakeContract.View view) {
        super(context, view);
    }

    @Override
    public void start() {

    }

    @Override
    public void getProposalDraft(String proposalId) {
        mView.showProgress("正在加载草稿");

        ProposalApi.getInstance(mContext).getProposalDraft(proposalId, new OnResponseListener<ResponseDraft>() {
            @Override
            public void onSuccess(ResponseDraft body, ResponsePage page) {
                mView.cancelProgress();
                if (body != null) {
                    mView.showEmpty(false, false, false);
                    mView.showToast("获取草稿成功");
                    mView.updateApplicant(null, body.getProposalApplicant());
                    //这里其实是只更新第一被保人
                    mView.updateInsured(null, body.getProposalFirstInsured());
                    if (body.getProposalApplicant() != null && !TextUtils.isEmpty(body.getProposalApplicant().clientAccountId)) {
                        mView.setOriginCustomerName(body.getProposalApplicant().name);
                    }
                    List<InsuranceEntity> riskList = body.getProposalRisks();
                    if (riskList != null) {
                        if (riskList.get(0) != null && riskList.get(0).isMain == 1) {
                            final BusinessConfig businessConfigDraft = riskList.get(0).businessConfig;
                            final int shouldSave = riskList.get(0).shouldSaveClient;
                            final int productId = body.getProposalRisks().get(0).productId;

                            ProposalApi.getInstance(mContext).getDetailMainProductDetails(productId, new OnResponseListener<ResponseMainDetail>() {
                                @Override
                                public void onSuccess(ResponseMainDetail mainDetailBody, ResponsePage page) {
                                    if (mainDetailBody != null) {
                                        List<InsuranceEntity> mRiskData = DataUtils.convertToInsuranceList(mainDetailBody);
                                        InsuranceEntity mainRisk = mRiskData.get(0);
                                        if (mainRisk != null && mainRisk.isMain == 1) {
                                            riskList.get(0).accSex = mainRisk.accSex;
                                            riskList.get(0).accOccupation = mainRisk.accOccupation;
                                            riskList.get(0).accMinAge = mainRisk.accMinAge;
                                            riskList.get(0).accMaxAge = mainRisk.accMaxAge;

                                            mView.updateInsurancePerson(body.getProposalApplicant(), body.getProposalFirstInsured());

                                            mView.addRiskViews(riskList);

                                            if (businessConfigDraft != null) {
                                                mView.updateBusinessConfig(businessConfigDraft);
                                            }
                                            List<InsuredEntity> insuredEntities = body.getProposalAllInsured();
                                            mView.updateOtherInsured(insuredEntities);
                                            mView.updateShowMoreInsureButton();
                                            mView.allowSaveCustomer(shouldSave == 1 ? true : false);

                                        }
                                    }
                                    mView.onDraftDownloadFinished();
                                }

                                @Override
                                public void onFailure(ResponseError error) {
                                }
                            }, mView);
                        }
                    } else {
                        Log.d("wangwang", "getProposalDraft() 5");
                    }
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.cancelProgress();
                if (!error.code.equals("-102")) {
                    mView.showToast("获取草稿失败");
                }

                if (error != null && "-102".equals(error.code)) {
                    mView.showEmpty(false, true, false);
                } else {
                    mView.showEmpty(false, false, true);
                }
            }
        }, mView);
    }

    //TODO
    @Override
    public void getCustomerDetail(String customerId) {
        mView.showProgress("正在加载客户");
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getCustomerDetail(customerId).compose(RxUtil.rxTransformer(mView)).subscribe(new Observer<CustomerDetailJson>() {
            @Override
            public void onComplete() {
            }

            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onError(Throwable e) {
                mView.cancelProgress();
                mView.showEmpty(false, false, true);
            }

            @Override
            public void onNext(CustomerDetailJson customerDetailJson) {
                mView.cancelProgress();
                if (customerDetailJson != null && customerDetailJson.error == null) {
                    mView.showEmpty(false, false, false);
                    DataUtils.reformatCustomerDetailReturn(customerDetailJson);
                    Customer customer = DataUtils.toCustomer(customerDetailJson.data);
                    if (customer != null) {
                        // 投保人与被保人一致，默认关系为本人,Code = 0
                        customer.setRelationWith(0);
                        mView.updateApplicant(customer, null);
                        mView.updateInsured(customer, null);
                        mView.allowSaveCustomer(false);
                        mView.setOriginCustomerName(customer.getName());
                        mView.updateInsurancePerson(DataUtils.toApplicant(customer), DataUtils.toInsured(customer));
                    }
                }
            }
        });
    }

    @Override
    public void getProductDetail(InsuranceEntity product, String productId, String age, int sex, int profession) {
        mView.showProgress("正在加载产品");
        ProposalApi.getInstance(mContext).getMainDetails(Integer.parseInt(productId), age, sex, profession, new OnResponseListener<ResponseMainDetail>() {
            @Override
            public void onSuccess(ResponseMainDetail body, ResponsePage page) {
                mView.cancelProgress();
                if (body != null) {
                    mView.showEmpty(false, false, false);
                    body.parseOptions();
                    List<InsuranceEntity> mRiskData = DataUtils.toInsuranceList(product, body);
                    mView.addRiskViews(mRiskData);
                    if (mRiskData.get(0) != null && mRiskData.get(0).isMain == 1) {
                        // 如果主险存在，显示制作计划书
                        mView.setMakeProposalEnabled(true);
                    }
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.cancelProgress();
                if (error != null && "-102".equals(error.code)) {
                    mView.showEmpty(false, true, false);
                } else {
                    mView.showEmpty(false, false, true);
                }
            }
        }, mView);
    }

    @Override
    public void getDefaultMainProductDetails(String productId) {
        mView.showProgress("正在加载产品");
        ProposalApi.getInstance(mContext).getDetailMainProductDetails(Integer.parseInt(productId), new OnResponseListener<ResponseMainDetail>() {
            @Override
            public void onSuccess(ResponseMainDetail body, ResponsePage page) {
                mView.cancelProgress();
                if (body != null) {
                    mView.showEmpty(false, false, false);
                    body.parseOptions();
                    /* 提取产品详情中附带的被保人信息，并初始化之*/
                    Customer customer = DataUtils.extractCustomer(body);
                    mView.initPersonAfterProductGetted(customer);
                    /* 初始化主险产品以及附带的附加险产品*/
                    List<InsuranceEntity> mRiskData = DataUtils.convertToInsuranceList(body);
                    mView.addRiskViews(mRiskData);
                    if (mRiskData.get(0) != null && mRiskData.get(0).isMain == 1) {
                        // 如果主险存在，显示制作计划书
                        mView.setMakeProposalEnabled(true);
                        mView.updateShowMoreInsureButton();
                        mView.updateBusinessConfig(mRiskData.get(0).businessConfig);
                    }
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.cancelProgress();
                if (error != null && "-102".equals(error.code)) {
                    mView.showEmpty(false, true, false);
                } else {
                    mView.showEmpty(false, false, true);
                }
            }
        }, mView);
    }

    @Override
    public void addMainProduct(Activity activity, ParamGetRisks param) {
        Bundle extras = new Bundle();
        extras.putSerializable(MainProductActivity.Arg_param, param);
        ActivityUtils.launchActivity(activity, MainProductActivity.class, extras);
    }

    //添加主险后，或者附加险后调用
    @Override
    public void addAdditionalViewAfterChoose(List<InsuranceEntity> dataList) {
        /* 添加主险或附加险*/
        if (dataList != null && dataList.size() > 0) {
            mView.addRiskViews(dataList);
            for (InsuranceEntity item : dataList) {
                if (item != null && item.isMain == 1) {
                    mView.updateBusinessConfig(item.businessConfig);
                    break;
                }
            }
            ifShowAddMoreInsuredView(dataList);
        }
    }

    private void ifShowAddMoreInsuredView(List<InsuranceEntity> dataList) {
        for (InsuranceEntity item : dataList) {
            if (item.isMain()) {
                mView.updateShowMoreInsureButton();
                return;
            }
        }
    }

    @Override
    public boolean isCompanyRegistered() {
        return AppContext.getCurrentUser().isRegisterCompany();
    }

    @Override
    public boolean isLogined() {
        return AppContext.getCurrentUser().isLogined();
    }

    @Override
    public void sendNotifyEventAfterSaveDraftOrMakeProposal() {
        ProposalListTabCheckedEvent event = new ProposalListTabCheckedEvent(); // 刷新建议书列表
        event.position = -1;
        EventBus.getDefault().post(event);

        EventRefreshProposalList customerProposalList = new EventRefreshProposalList(); //
        EventBus.getDefault().post(customerProposalList);
    }

    @Override
    public void checkProposal(boolean allowSave, Customer customer, String originCustomerName, ProposalEntity proposal, boolean isFinalVerify) {
        if (proposal == null || proposal.insured == null || proposal.insured.size() == 0) {
            return;
        }
        if (proposal.insured.get(0) == null || proposal.insured.get(0).risk == null || proposal.insured.get(0).risk.size() == 0) {
            // 没有一款产品存在，不必做校验
            return;
        }

        mView.showProgress("正在生成计划书...");
        ProposalApi.getInstance(mContext).verifyProposal(ProposalParam.param(proposal), new OnResponseListener<List<String>>() {
            @Override
            public void onSuccess(List<String> body, ResponsePage page) {
                if (isFinalVerify) {
                    doMakeProposal(allowSave, customer, originCustomerName, proposal);
                } else {
                    mView.cancelProgress();
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.cancelProgress();
                if (error != null && error.flag == 1) {
                    // 校验错误，提示
                    mView.showTipDialog(error.message);
                }
            }
        }, mView);
    }

    /**
     * 投被保人关系检查（选择时校验；生成时校验）
     * 1.）选择时校验：是否为同一关系（本人or夫妻）
     * 2.）生成时校验：1、投被保人关系是否填写 2、多被保人关系是否重复（本人or夫妻）
     *
     * @param resRelationCode -1 -> 生成时校验；  其他 -> 选择时校验（0  or 1）
     * @param entity
     * @return
     */
    @Override
    public boolean checkRelation(int resRelationCode, ProposalEntity entity) {
        if (entity == null || entity.insured == null) {
            return false;
        }
        List<InsuredEntity> insured = entity.insured;
        boolean hasRelation0 = false;
        boolean hasRelation1 = false;
        for (InsuredEntity insuredEntity : insured) {
            if (resRelationCode == -1) {
                if (insuredEntity.relation == -1) {
                    mView.showToast("还有投被保人关系未设置");
                    return false;
                } else if (insuredEntity.relation == 0) {
                    if (hasRelation0) {
                        mView.showTipDialog("被保人不能与其他被保人为同一人");
                        return false;
                    } else {
                        hasRelation0 = true;
                    }
                } else if (insuredEntity.relation == 1) {
                    if (hasRelation1) {
                        mView.showTipDialog("被保人不能与其他被保人为同一人");
                        return false;
                    } else {
                        hasRelation1 = true;
                    }
                }

            } else {
                if (insuredEntity.relation == resRelationCode) {
                    mView.showTipDialog("被保人不能与其他被保人为同一人");
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void saveToProposalDraft(ProposalEntity proposal) {
        mView.showProgress("正在保存草稿...");
        ProposalApi.getInstance(mContext).saveProposalToDraft(DraftParam.param(proposal), new OnResponseListener<ResponsePickNum>() {
            @Override
            public void onSuccess(ResponsePickNum body, ResponsePage page) {
                mView.cancelProgress();
                try {
                    mView.showToast("保存到草稿");
                    sendNotifyEventAfterSaveDraftOrMakeProposal();
//                    if (!mView.isProposalDraft()) {
                    mView.finishCustomActivity();
                    mView.checkToProposalList();
//                    } else {
                    // 草稿为了保证最新的列表，在列表更新完成后;在MakeProposalActivity中的onEvent中关闭
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    mView.setDraftSaving(false);
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.cancelProgress();
                mView.setDraftSaving(false);
                try {
                    mView.showToast("保存草稿失败");
                } catch (Exception e) {
                    e.printStackTrace();
                }
                mView.finishActivity();
                mView.checkToProposalList();
            }
        }, mView);
    }

    @Override
    public void makeProposal(ProposalEntity proposal) {
        ProposalApi.getInstance(mContext).makeProposal(ProposalParam.param(proposal), new OnResponseListener<ResponseMakeProposal>() {
            @Override
            public void onSuccess(ResponseMakeProposal body, ResponsePage page) {
                mView.cancelProgress();
                if (body != null) {
                    mView.showToast("制作计划书成功");
                    sendNotifyEventAfterSaveDraftOrMakeProposal();
                    ArgProposalDetail mArgDetail = new ArgProposalDetail();
                    mArgDetail.proposalId = body.pickNum;
                    mArgDetail.proposalName = proposal.proposalName;
                    mArgDetail.applicantName = proposal.applicant.name;
                    mArgDetail.previewUrl = body.previewUrl;
                    mArgDetail.shareUrl = body.viewUrl;
                    mArgDetail.shareUrlWeXin = body.viewUrl;
                    mArgDetail.isNewProposal = true;
                    mView.gotoProposalDetail(mArgDetail);
                    mView.finishActivity();
                }
            }

            @Override
            public void onFailure(ResponseError error) {
                mView.cancelProgress();
                mView.showToast("制作计划书失败");
            }
        }, mView);
    }

    @Override
    public void createCustomer(Customer customer, ProposalEntity proposal) {
        CustomerDetail param = DataUtils.toCustomerDetail(customer);
        param.setBirthday(param.getBirthday() / 1000); /* 生日的上传单位为秒， 转换为秒*/
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.createCustomer(param).compose(RxUtil.rxTransformer(mView)).subscribe(new CustomerSubscriber(proposal));
    }

    @Override
    public void updateCustomer(Customer customer, ProposalEntity proposal) {
        CustomerDetail param = DataUtils.toCustomerDetail(customer);
        param.setBirthday(param.getBirthday() / 1000); /* 生日的上传单位为秒， 转换为秒*/
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.updateCustomer(customer.getCustomerId(), param).compose(RxUtil.rxTransformer(mView)).subscribe(new CustomerSubscriber(proposal));
    }

    @Override
    public void doMakeProposal(boolean allowSave, Customer customer, String originCustomerName, ProposalEntity proposal) {
        if (allowSave) {
            /* 需要保存到客户列表*/
            if (customer == null) {
                makeProposal(proposal);
            } else {
                /**
                 * 更新客户，只更新除姓名外的信息，如性别，年龄，生日等
                 * 因此在从客户导入、从客户进入，从草稿进入且带有导入客户信息时，需要更新客户姓名为原始姓名
                 * 原始性别保存在originCustomerName中，导入客户的原始姓名保存在Customer的originName中
                 */
                String customerId = customer.getCustomerId();
                if (TextUtils.isEmpty(customerId)) {
                    /* 没有ID, 则新建客户*/
                    createCustomer(customer, proposal);
                } else {
                    /* 有ID,则更新客户*/
                    if (!TextUtils.isEmpty(originCustomerName)) {
                        customer.setName(originCustomerName);
                    } else {
                        if (!TextUtils.isEmpty(customer.getOriginName())) {
                            customer.cloneToName();
                        }
                    }
                    updateCustomer(customer, proposal);
                }
            }
        } else {
            makeProposal(proposal);
        }
    }

    private class CustomerSubscriber implements Observer<CustomerCRUDRetJson> {
        private static final String errorMsg = "生成计划书失败";
        private ProposalEntity proposal;

        public CustomerSubscriber(ProposalEntity proposal) {
            this.proposal = proposal;
        }

        @Override
        public void onComplete() {

        }

        @Override
        public void onSubscribe(Disposable d) {

        }

        @Override
        public void onError(Throwable e) {
            e.printStackTrace();
            mView.cancelProgress();
            mView.showToast(errorMsg + e.getMessage());
        }

        @Override
        public void onNext(CustomerCRUDRetJson customerCRUDRetJson) {
            if (customerCRUDRetJson == null || customerCRUDRetJson.data == null) {
                mView.cancelProgress();
                mView.showToast(errorMsg);
                return;
            }
            if (customerCRUDRetJson.error != null) {
                mView.cancelProgress();
                mView.showToast(errorMsg + ",错误代码为:"
                        + customerCRUDRetJson.error.message);
                return;
            }
            EventBus.getDefault().post(new EventCustomerListRefresh());
            if (proposal != null && proposal.applicant != null) {
                /* 保存到客户列表后的ID传给投保人 */
                proposal.applicant.clientAccountId = customerCRUDRetJson.data.customerId;
            }
            makeProposal(proposal);
        }
    }

    public void getAdditionalProducts(int productId, MakeProposalActivity.GetAttachRiskListener listener) {
        EBTAPI ebtapi = AppInitService.getEbtApi();
        ebtapi.getChanShuoHuiList(productId)
                /*.observeOn(AndroidSchedulers.mainThread())
                .subscribeOn(Schedulers.io())*/
                .compose(RxUtil.rxTransformer(mView))
                .subscribe(new Observer<ResponseBodyBase<List<ResponseChanShuoItem>>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(ResponseBodyBase<List<ResponseChanShuoItem>> value) {
                        if (value != null && value.data != null && value.data.size() > 0) {
                            listener.onResult(value.data);
                        } else {
                            listener.onResult(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    @Override
    public void getProductProperties(int productId) {
        ProposalApi.getInstance(mContext).getProductProperties(productId, new OnResponseListener<List<ResponseProductProperties>>() {
            @Override
            public void onSuccess(List<ResponseProductProperties> body, ResponsePage page) {
                //显示图片
                if (body != null) {
                    ResponseProductProperties productProperties = null;
                    for (int i = 0; i < body.size(); i++) {
                        productProperties = body.get(i);
                        if ("UnderwriteRuleTipImgUrl".equalsIgnoreCase(productProperties.getFieldName())) {
                            String val = productProperties.getValue();
                            //显示图片
                            List<String> urls = GsonUtil.parseJsonArrayWithGson(val, String.class);
                            if (urls != null && urls.size() > 0) {
                                mView.displayProductPropertiyImg(urls.get(0));
                            }
                            break;
                        }
                    }
                }
            }

            @Override
            public void onFailure(ResponseError error) {

            }
        }, mView);
    }
}
